package com.crazymaker.springcloud.base.security.configurer;

import com.crazymaker.springcloud.base.security.filter.JwtAuthenticationFilter;
import com.crazymaker.springcloud.base.security.handler.AuthFailureHandler;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;

public class JwtAuthConfigurer<T extends JwtAuthConfigurer<T, B>, B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T, B> {

    private JwtAuthenticationFilter jwtFilter;

    public JwtAuthConfigurer() {
        jwtFilter = new JwtAuthenticationFilter();
    }

    @Override
    public void configure(B builder) throws Exception {
        AuthenticationManager sharedObject = builder.getSharedObject(AuthenticationManager.class);
        jwtFilter.setAuthenticationManager(sharedObject);
        jwtFilter.setFailureHandler(new AuthFailureHandler());

        // 配置过滤器
        JwtAuthenticationFilter filter = postProcess(jwtFilter);
        builder.addFilterBefore(filter, LogoutFilter.class);
    }

    public JwtAuthConfigurer<T, B> permissiveRequestUrls(String... urls) {
        jwtFilter.setPermissiveUrl(urls);
        return this;
    }

    public JwtAuthConfigurer<T, B> tokenValidSuccessHandler(AuthenticationSuccessHandler successHandler) {
        jwtFilter.setSuccessHandler(successHandler);
        return this;
    }
}
